package com.qicheng.wlhyspider.hainan.conroller;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qicheng.wlhyspider.common.Constants;
import com.qicheng.wlhyspider.common.PageResult;
import com.qicheng.wlhyspider.common.RedisUtils;
import com.qicheng.wlhyspider.hainan.dao.CompanyRepository;
import com.qicheng.wlhyspider.hainan.entity.CompanyEntity;
import com.qicheng.wlhyspider.hainan.mapper.CompanyMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/hainan/company")
@Slf4j
public class CompanyController {
    private final CompanyRepository companyRepository;
    private final CompanyMapper companyMapper;

    private final RedisUtils redisUtils;

    public CompanyController(CompanyRepository companyRepository, CompanyMapper companyMapper, RedisUtils redisUtils) {
        this.companyRepository = companyRepository;
        this.companyMapper = companyMapper;
        this.redisUtils = redisUtils;
    }

    @GetMapping("/save")
    public String save(@RequestParam("page") Integer page) {
        return saveAll(page);
    }

    private String saveAll(Integer page) {
        String token = redisUtils.get(Constants.TOKEN) + "";
        HttpResponse httpResponse = HttpUtil.createGet("http://wlhy.mot.gov.cn/hainan/basis/company/list?page="+page+"&limit=10")
                .header("x-auth-token", token)
                .execute();
        if (httpResponse.getStatus() == 200) {
            String body = httpResponse.body();
            PageResult pageResult = JSONObject.parseObject(JSONObject.toJSONString(JSONObject.parse(body)), PageResult.class);
            PageResult.ResultDTO result = pageResult.getResult();
            List<CompanyEntity> list = JSONArray.parseArray(JSONArray.toJSONString(result.getRecords()), CompanyEntity.class);
            companyMapper.insertBatchSomeColumn(list);
            if (page < result.getPages()) {
                page++;
                return save(page);
            }

        } else if (httpResponse.getStatus() == 203) {
            log.info("登录信息失效");
            return "返回：登录信息失效";
        } else {
            log.info("查询失败");
            return "返回：查询失败";
        }
        log.info("返回：插入成功");
        return "插入成功";
    }
}
